//
//  ViewController.m
//  FindJob
//
//  Created by 233 on 16/2/29.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "ViewController.h"
#import "UserModel.h"
#import "ItemModel.h"
#import "AlertView.h"
#import "RecruitmentAPIManger.h"
#import "InviteInformationVCViewController.h"

#define kItemCellEdgeDistance 10
#define kItemMinDistanceOfLine 20
#define kItemInteritemDistance 15
#define kItemsCountInLines 3

static NSString *const kInviteInformationVC = @"InviteInformationVC";
static NSString *const kReusableTableCell = @"tableCell";
static NSString *const kLoginViewController = @"LoginViewController";
static NSString *const kReusableCellWithReuseIdentifier = @"kcellid";
@interface TtemCollectionCell()
@property (weak, nonatomic) IBOutlet UIImageView *imagView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@end

@implementation TtemCollectionCell 

@end

@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property(nonatomic,copy)NSArray *itemarr;
@property(nonatomic,copy)NSArray *itemSegueIdentifiers;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)RecruitmentAPIManger *recruitmentAPIManger;
@property(nonatomic,copy)NSArray *dataSource;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,copy)NSDictionary *allNameDict;

- (void)initializeDataSource;     /**< 初始化数据源 */
- (void)initializeUserIntefcace;  /**< 初始化用户界面 */
- (void)initAnimationViewBlock;
@end

@implementation ViewController
- (void)dealloc{
    [[UserModel shareUserModel] removeObserver:self forKeyPath:@"isLogin"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeUserIntefcace];
}
- (void)initializeDataSource{
    
    int page = 1;
    NSNumber *num = [NSNumber numberWithInt:page];
    NSDictionary *parameter = @{@"sortname":@"0",@"page":num};
    
    [self.recruitmentAPIManger startRecruitmentInfoWithParameters:parameter responds:^(RespondsStatus status, NSString *message, id resultData) {
        if(status == RespondsStatusSuccess){
       
            NSMutableArray *companyNames = [[NSMutableArray alloc] init];
            
            for (int i = 0; i < [resultData count]; i++) {
                
                NSString *companyName = resultData[i][@"company"];
                if (![companyNames containsObject:companyName]) {
                    [companyNames addObject:companyName];
                }
                _dataSource = companyNames;
                
            }
            [self.tableView reloadData];
            
            NSMutableDictionary *resultDict = [[NSMutableDictionary alloc] init];
            for(int i = 0 ; i < [companyNames count];i++) {
              NSMutableArray *infoArr = [NSMutableArray array];
                for (int j = 0; j < [resultData count]; j++) {
                    NSString *name = resultData[j][@"company"];
                    if ([name isEqualToString:companyNames[i]]) {
                        [infoArr addObject:resultData[j]];
                    }
                }
                [resultDict setObject:infoArr forKey:companyNames[i]];
            }
            _allNameDict = resultDict;
        }
        
        NSLog(@"message = %@",message);
    }];
   
    
  

}
- (void)initializeUserIntefcace{
    [self addObservers];
    self.collectionView.autoresizesSubviews = YES;
    self.collectionView.bounces = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    // 初始化定时器
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(respondsToTimer) userInfo:nil repeats:YES];
    // 启动定时器
    _timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:0.1];
    // 暂停定时器
//    _timer.fireDate = [NSDate distantFuture];
    
//    [self initAnimationViewBlock];

    /** 高级动画 */
//    _imageView.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:@"main_advertisement"],[UIImage imageNamed:@"main_advertisement1"] ,nil];
//    _imageView.animationDuration = 5.0f;
//    _imageView.animationRepeatCount = 0;
//    [_imageView startAnimating];
//    
//    CABasicAnimation *rotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.y"];
//    rotation.fromValue = @(0);
//    rotation.toValue = @(M_PI);
//    rotation.duration = 5.0f;
//    rotation.repeatCount = HUGE;
//    rotation.removedOnCompletion = YES;
//    rotation.cumulative = YES;
//    [_imageView.layer addAnimation:rotation forKey:rotation.keyPath];
    
    
}
//
#pragma mark -- timer
- (void)respondsToTimer{
    [self initAnimationViewBlock];
}
- (void)initAnimationViewBlock{
    
    [UIView animateWithDuration:3.0f animations:^{
        //
        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:_imageView cache:YES];
        if ([_imageView.image isEqual:[UIImage imageNamed:@"main_advertisement"]]) {
            _imageView.image = [UIImage imageNamed:@"main_advertisement1"];
        }else{
            _imageView.image = [UIImage imageNamed:@"main_advertisement"];
        }
        
        [UIView commitAnimations];
    } completion:^(BOOL finished) {
//        [self initAnimationViewBlock];/** 循环调用会占用很大内存 */
        // 启动定时器
        _timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:3.0];
        
    }];
    
}
#pragma mark -- private

- (IBAction)loginActionBtn:(UIButton *)sender {
    if (![UserModel shareUserModel].isLogin) {
        [self performSegueWithIdentifier:kLoginViewController sender:self];
    }else{
        [self showAlertViewControllerWithTarget:self title:@"温馨提示" message:@"您确定要注销么?"];
    }
}

#pragma mark *** private ***
- (void)showAlertViewControllerWithTarget:(id _Nonnull)target title:(NSString *_Nonnull)title message:(NSString *_Nonnull)message{
    
     UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        AlertView *alertView = [[AlertView alloc] initWithTitle:@"已退出"];
        [alertView show];
        [UserModel shareUserModel].isLogin = NO;
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [target presentViewController:alertController animated:YES completion:nil];
}

- (void)addObservers{
    UserModel *model = [UserModel shareUserModel];
    [model addObserver:self forKeyPath:@"isLogin" options:NSKeyValueObservingOptionNew context:nil];
    
}
#pragma mark ***KVO observer ***
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if (object == [UserModel shareUserModel] && [keyPath isEqualToString:@"isLogin"]) {
        NSLog(@"change = %@",change);
        BOOL isLogin = [change[@"new"] boolValue];
        if (isLogin) {
            [self.loginButton setImage:[UIImage imageNamed:@"title_logout" ]forState:UIControlStateNormal];
        }else{
            [self.loginButton setImage:[UIImage imageNamed:@"title_login" ]forState:UIControlStateNormal];
        }
    }
}

#pragma mark --UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kReusableTableCell];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kReusableTableCell];
    }
    
    
    cell.textLabel.text = _dataSource[indexPath.row];
    
    cell.accessoryType =  UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

#pragma mark --UITableViewDelegate
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return @"名企招聘";
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    [self.view.window.layer removeAllAnimations];
    //转场动画
    CATransition *transition = [CATransition new];
    //持续时间
    transition.duration = 0.7f;
    //线性规律
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    transition.type = @"pageCurl";
    transition.subtype = kCATransitionFromLeft;
    
    //添加动画
    [self.view.window.layer addAnimation:transition forKey:Nil];
    [UserModel shareUserModel].isSelcetedTable = YES;
    [self performSegueWithIdentifier:kInviteInformationVC sender:self];
}

#pragma mark -- Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    if ([segue.destinationViewController isKindOfClass:[InviteInformationVCViewController class]]) {
        InviteInformationVCViewController *iiVc = segue.destinationViewController;
        NSString *name = _dataSource[self.tableView.indexPathForSelectedRow.row];
        iiVc.infoArr = _allNameDict[name];
    }
    
}





#pragma mark *** UICollectionViewDataSource ***
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.itemarr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    TtemCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kReusableCellWithReuseIdentifier forIndexPath:indexPath];
    ItemModel *model = self.itemarr[indexPath.item];
//    [UIImage imageNamed:<#(nonnull NSString *)#>] 图片会在内存中缓存，
//    [UIImage imageWithContentsOfFile:<#(nonnull NSString *)#>];图片直接从文件中读取。
    
    cell.imagView.image = [UIImage imageNamed:model.imageName];
    cell.titleLabel.text = model.title;
    
    return cell;
    
}
#pragma mark *** UICollectionViewDelegateFlowLayout ***
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(kItemCellEdgeDistance, kItemCellEdgeDistance, kItemCellEdgeDistance, kItemCellEdgeDistance);
//    return UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat collectionView_width = collectionView.bounds.size.width;
    CGFloat collectionView_height = collectionView.bounds.size.height;
    // 10 是边距 5 是行间距
    
    CGFloat cellWidth =(collectionView_width - kItemCellEdgeDistance * 2 - (kItemsCountInLines - 1)* kItemInteritemDistance) / kItemsCountInLines;
    
    NSInteger numberOfLines = self.itemarr.count / kItemsCountInLines;
    
    CGFloat cellHeight = (collectionView_height - kItemCellEdgeDistance * 2 - (numberOfLines - 1) * kItemInteritemDistance) /numberOfLines;
    
    return CGSizeMake(cellWidth, cellHeight);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return kItemInteritemDistance;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return kItemMinDistanceOfLine;
}
#pragma mark *** UICollectionViewDelegate ***
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    [UserModel shareUserModel].isSelcetedTable = NO;
    // 执行联系
    ItemModel *model = self.itemarr[indexPath.item];
    if (model.isRequireLogin && ![UserModel shareUserModel].isLogin) {
        // 切换至登录界面
        
        AlertView *alertView = [[AlertView alloc] initWithTitle:@"请先登录"];
        [alertView show];
        [self performSegueWithIdentifier:kLoginViewController sender:self];
        
    }else{
        [self performSegueWithIdentifier:self.itemSegueIdentifiers[indexPath.item] sender:self];
    }
    
    
}
#pragma mark *** UIbutton action ***
- (IBAction)unwindToMainViewController:(UIStoryboardSegue *)unwindSegue{
    
}



#pragma mark *** getters ***
- (RecruitmentAPIManger *)recruitmentAPIManger{
    if (!_recruitmentAPIManger) {
        _recruitmentAPIManger = [[RecruitmentAPIManger alloc] init];
    }
    return _recruitmentAPIManger;
}

- (NSArray *)itemSegueIdentifiers{
    if (!_itemSegueIdentifiers) {
        _itemSegueIdentifiers = @[@"InviteInformationVC",@"InterViewSkillVC",@"SalaryQuaryVC",@"InterViewScheduleVC",@"PersonalResumeVC",@"MoreOptionalVC"];
    }
    return _itemSegueIdentifiers;
}
- (NSArray *)itemarr{
    if (!_itemarr) {
        ItemModel *itemModel = [[ItemModel alloc] init];
        _itemarr = [itemModel gainItemModels];
    }
    return _itemarr;
}
- (NSArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [[NSArray alloc] init];
    }
    return _dataSource;
}
@end
